package redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author csp 2021-02-20
 */
public class PubSubDemo {
    private static JedisPool jedisPool;

    static Runnable publisher = () -> {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Jedis jedis = jedisPool.getResource();   //连接池中取出一个连接
        while (true) {
            String line = null;
            try {
                line = reader.readLine();
                if (!"quit".equals(line)) {
                    jedis.publish("mychannel", line);   //从 mychannel 的频道上推送消息
                } else {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };
    static Runnable subThread = () -> {
        Subscriber subscriber = new Subscriber();
        String channel = "mychannel";
        System.out.println(String.format("subscribe redis, channel %s, thread will be blocked", channel));
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();   //取出一个连接
            jedis.subscribe(subscriber, channel);    //通过subscribe 的api去订阅，入参是订阅者和频道名
        } catch (Exception e) {
            System.out.println(String.format("subsrcibe channel error, %s", e));
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    };
    public static void main(String[] args) {
        // 连接redis服务端
        jedisPool = new JedisPool(new JedisPoolConfig(), "10.168.4.237", 6379);
        System.out.println(String.format("redis pool is starting, redis ip %s, redis port %d", "10.168.4.237", 6379));
        new Thread(subThread).start();
        new Thread(publisher).start();
    }
    //冒泡
}
